//
//  ClubGlobalTool.swift
//  77Club
//
//  Created by Apple on 2024/9/18.
//

import Foundation
import Kingfisher
import CommonCrypto
import Photos
import SafariServices

class ClubGlobalTool: NSObject {
    
    static let shared       = ClubGlobalTool()
    public var textColorStr = ["#FF7500","#5AB530","#36C097"]
    public var bgColorStr = ["#F8EEE6","#EDF4EC","#E8F4F2"]
    public var borderColor_One = ["#AE2C2C","#AD5320","#AFA120","#5FB24A","#3BB15C","#4DB181","#5E95B5","#5174B8","#7E51B8","#B85176"]
    public var borderColor_Two = ["#B53030","#B55830","#B58030","#A2B530","#7AB530","#30B58D","#309DB5","#3065B5","#303DB5","#A230B5"]
    public var borderColor_Three = ["#C03636","#C06836","#C08136","#C0B336","#5AC036","#36C08F","#36C0B8","#36A8C0","#365DC0","#5A36C0"]
    public var newGameList = false
    public var dynamicShareTitle = "乐玩游戏圈动态，快来围观！"
    public var dynamicShareDes = "他刚刚发布了新动态，又发现了一款超好玩的游戏，精彩不断！"
    public var forumShareDes = "你的小伙伴都在这结识更多志同道合的游戏玩家！论坛分享内容！"
    public var postShareTitle = "分享游戏快乐，就在乐玩"
    public var likeColor: UIColor = "#E65C6E".toColor
    /// 计算缓存
    func queryCacheSize() -> Double {
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first,
              let fileArray = FileManager.default.subpaths(atPath: cachePath)
        else {return 0}
        var size = 0
        fileArray.forEach {
            let path = cachePath + ("/\($0)")
            if let floder = try? FileManager.default.attributesOfItem(atPath: path) {
                for (key, fileSize) in floder {
                    // 累加文件大小
                    if key == FileAttributeKey.size {
                        size += (fileSize as AnyObject).integerValue
                    }
                }
            }
        }
        let totalCache = Double(size)/1024.00/1024.00
        return totalCache
    }
    
    /// 清理缓存
    func clearCache(_ completion: @escaping (()->Void)) {
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first,
              let fileArray = FileManager.default.subpaths(atPath: cachePath)
        else {return}
        fileArray.forEach {
            let path = cachePath + ("/\($0)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                    let cache = KingfisherManager.shared.cache
                    cache.clearDiskCache()
                    cache.clearMemoryCache()
                    cache.cleanExpiredDiskCache()
                } catch let error {
                    MusePrint(error.localizedDescription)
                }
            }
        }
        DispatchQueue.main.async {
            completion()
        }
    }
    
    /// AES-128加密
    func AES128Encrypt(plainText: String, key: String) -> String? {
        // 密钥长度为 128 位
        let keyLength = kCCKeySizeAES128
        var keyPtr = [CChar](repeating: 0, count: keyLength + 1)
        key.getCString(&keyPtr, maxLength: keyLength + 1, encoding: .utf8)
        
        // 将明文转换为 Data
        guard let data = plainText.data(using: .utf8) else {
            return nil
        }
        let dataLength = data.count
        
        // 为加密后的数据创建缓冲区
        let bufferSize = dataLength + kCCBlockSizeAES128
        var buffer = [UInt8](repeating: 0, count: bufferSize)
        var numBytesEncrypted: size_t = 0
        
        // 执行加密操作
        let cryptStatus = CCCrypt(CCOperation(kCCEncrypt),
                                  CCAlgorithm(kCCAlgorithmAES128),
                                  CCOptions(kCCOptionPKCS7Padding | kCCOptionECBMode),
                                  keyPtr,
                                  keyLength,
                                  nil,
                                  (data as NSData).bytes,
                                  dataLength,
                                  &buffer,
                                  bufferSize,
                                  &numBytesEncrypted)
        
        if cryptStatus == kCCSuccess {
            let resultData = Data(bytes: buffer, count: numBytesEncrypted)
            // 将加密后的数据进行 Base64 编码
            var base64String = resultData.base64EncodedString()
            // 替换 "+" 为 "_"
            base64String = base64String.replacingOccurrences(of: "+", with: "_")
            return base64String
        }
        
        return nil
    }

    func convertToJsonData(_ dict: [String: Any]) -> String? {
        do {
            // 将字典转换为 JSON 数据
            let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
            
            // 将 JSON 数据转换为字符串
            if var jsonString = String(data: jsonData, encoding: .utf8) {
                // 去掉字符串中的空格
                jsonString = jsonString.replacingOccurrences(of: " ", with: "")
                // 去掉字符串中的换行符
                jsonString = jsonString.replacingOccurrences(of: "\n", with: "")
                
                return jsonString
            }
        } catch {
            print("Error converting to JSON: \(error)")
        }
        return nil
    }

    func encodeToBase64String(image: UIImage) -> String? {
        if let imageData = image.pngData() {
            return imageData.base64EncodedString(options: .lineLength64Characters)
        }
        return nil
    }

}


//MARK: 图片下载
extension ClubGlobalTool {
    
    // 下载图片
    func downloadImage(from url: URL) {
        let session = URLSession.shared
        let task = session.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print("下载图片失败: \(error)")
                return
            }
            guard let imageData = data, let image = UIImage(data: imageData) else {
                print("无法解析图片数据")
                return
            }
            // 请求权限并保存图片到相册
            self.saveImageToPhotosAlbum(image)
        }
        task.resume()
    }

    // 保存图片到相册
    func saveImageToPhotosAlbum(_ image: UIImage) {
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.saveError), nil)
            } else {
                print("无权限保存到相册")
            }
        }
    }

    // 保存图片后的回调
    @objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            print("保存失败: \(error.localizedDescription)")
        } else {
            "图片保存成功".toast_success
            print("图片已成功保存到相册")
        }
    }
}


//MARK: 图片识别颜色
extension UIImage {
    
    // 获取图片的主颜色
    func dominantColor() -> UIColor? {
        guard let cgImage = self.cgImage else { return nil }

        // 缩小图片的尺寸
        let width = 10
        let height = 10
        let bitmapBytesPerRow = width * 4
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapData = malloc(width * height * 4)
        defer { free(bitmapData) }

        guard let context = CGContext(
            data: bitmapData,
            width: width,
            height: height,
            bitsPerComponent: 8,
            bytesPerRow: bitmapBytesPerRow,
            space: colorSpace,
            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
        ) else { return nil }

        // 在上下文中绘制图像
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))

        guard let data = context.data else { return nil }

        // 提取所有像素的颜色数据
        let pixelData = data.bindMemory(to: UInt8.self, capacity: width * height * 4)
        var colorCount: [UIColor: Int] = [:]

        for x in 0..<width {
            for y in 0..<height {
                let pixelIndex = (y * width + x) * 4
                let r = CGFloat(pixelData[pixelIndex]) / 255.0
                let g = CGFloat(pixelData[pixelIndex + 1]) / 255.0
                let b = CGFloat(pixelData[pixelIndex + 2]) / 255.0
                let a = CGFloat(pixelData[pixelIndex + 3]) / 255.0

                // 忽略透明像素
                guard a > 0.1 else { continue }

                let color = UIColor(red: r, green: g, blue: b, alpha: 1.0)
                colorCount[color, default: 0] += 1
            }
        }

        // 找出出现次数最多的颜色
        let dominantColor = colorCount.max { $0.value < $1.value }?.key
        return dominantColor
    }


}

//MARK: 图片下载
extension ClubGlobalTool {
    
    func downloadImage(from urlString: String, completion: @escaping (UIImage?) -> Void) {
        guard let url = URL(string: urlString) else {
            completion(nil)
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data, let image = UIImage(data: data) {
                completion(image)
            } else {
                completion(nil)
            }
        }.resume()
    }

    // 获取图片的主色调
    func getDominantColor(from image: UIImage) -> UIColor? {
        guard let cgImage = image.cgImage else { return nil }
        
        // 将图片缩小以减少计算量
        let width = 50
        let height = 50
        let context = CGContext(data: nil, width: width, height: height,
                                bitsPerComponent: 8, bytesPerRow: width * 4,
                                space: CGColorSpaceCreateDeviceRGB(),
                                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
        
        // 绘制缩小后的图片
        context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
        
        // 获取像素数据
        guard let pixelBuffer = context?.data else { return nil }
        
        let data = UnsafePointer<UInt8>(pixelBuffer.assumingMemoryBound(to: UInt8.self))
        
        // 创建一个字典统计每种颜色的数量
        var colorFrequency: [UIColor: Int] = [:]
        
        for x in 0..<width {
            for y in 0..<height {
                let offset = 4 * (x + y * width)
                let r = data[offset]
                let g = data[offset + 1]
                let b = data[offset + 2]
                let a = data[offset + 3]
                
                if a > 0 {
                    let color = UIColor(red: CGFloat(r) / 255.0,
                                        green: CGFloat(g) / 255.0,
                                        blue: CGFloat(b) / 255.0,
                                        alpha: 1.0)
                    
                    colorFrequency[color, default: 0] += 1
                }
            }
        }
        
        // 返回出现次数最多的颜色
        return colorFrequency.max { $0.value < $1.value }?.key
    }
}


//MARK: 分享
extension ClubGlobalTool {
    //shareType 1.微信聊天 2.朋友圈
    func shareDetailInfo(title: String, des: String, imgUrl: String, shareUrl: String, shareType: Int) {
        
        downloadImage(from: imgUrl) { [weak self] image in
            guard let image = image else {
                    print("图片下载失败")
                    return
            }
            // 确保在主线程上分享
            DispatchQueue.main.async {
                self?.shareToWechat(title: title, des: des, image: image, shareUrl: shareUrl, shareType: shareType)
            }
        }
    }
    
    func shareToWechat(title: String, des: String, image: UIImage, shareUrl: String, shareType: Int) {
        // 创建分享内容
        let message = WXMediaMessage()
        message.title = title
        message.description = des
            
        // 设置缩略图
        let thumbnail = image // 使用你项目中的图片
        message.setThumbImage(thumbnail)
            
        // 创建网页分享对象
        let webpageObject = WXWebpageObject()
        webpageObject.webpageUrl = shareUrl  // 要分享的网页链接
        message.mediaObject = webpageObject
            
        // 创建发送请求
        let req = SendMessageToWXReq()
        req.message = message
        if shareType == 1 {
            req.scene = Int32(WXSceneSession.rawValue) // WXSceneSession表示分享到微信聊天
        }else if shareType == 2 {
            req.scene = Int32(WXSceneTimeline.rawValue) // WXSceneSession表示分享到朋友圈
        }
        // 发送请求
        WXApi.send(req) { success in
            if success {
                print("分享请求发送成功")
            } else {
                print("分享请求发送失败")
            }
        }
    }
    
    //QQ分享
    func shareToQQ(title: String, description: String, imageUrl: String, url: String) {
        TencentOAuth.setIsUserAgreedAuthorization(true)
        let newsObj = QQApiNewsObject(url: URL(string: url), title: title, description: description, previewImageURL: URL(string: imageUrl), targetContentType: .news)
        let req = SendMessageToQQReq(content: newsObj)
        QQApiInterface.send(req)
    }
}


//MARK: 时间转换
extension ClubGlobalTool {
    
    func timeDescription(from dateString: String, _ type: Int = 1) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        // 将字符串转换为 Date
        guard let date = dateFormatter.date(from: dateString) else {
            print("时间格式错误")
            return dateString
        }

        let now = Date()
        let interval = now.timeIntervalSince(date) // 时间间隔，单位：秒

        if interval <= 60 {
            if type == 2{
                return "刚刚"
            }else{
                return "刚刚发布"
            }            
        } else if interval <= 3600 { // 小于1小时
            let minutes = Int(interval / 60)
            return "\(minutes)分钟前"
        } else if interval <= 86400 { // 小于1天
            let hours = Int(interval / 3600)
            return "\(hours)小时前"
        } else if interval <= 2592000 { // 小于30天
            let days = Int(interval / 86400)
            return "\(days)天前"
        } else if interval <= 31104000 { // 小于1年
            let months = Int(interval / 2592000)
            return "\(months)月前"
        } else {
            let years = Int(interval / 31104000)
            return "\(years)年前"
        }
    }
}

//MARK: 字符串获取里面的数字加减
extension ClubGlobalTool {
    
    func calculateNumberInString(text: String) -> String {

        var temp = text
        if let range = temp.range(of: "\\d+", options: .regularExpression) {
            // 提取数字部分
            if let number = Int(temp[range]) {
                // 数字加 1
                let incrementedNumber = number + 1
                // 替换原来的数字
                temp.replaceSubrange(range, with: "\(incrementedNumber)")
                return temp
            }
        }
        return text
    }
    
    func subtractionNumberInString(text: String) -> String {

        var temp = text
        if let range = temp.range(of: "\\d+", options: .regularExpression) {
            // 提取数字部分
            if let number = Int(temp[range]) {
                // 数字减 1
                let incrementedNumber = number - 1
                // 替换原来的数字
                temp.replaceSubrange(range, with: "\(incrementedNumber)")
                return temp
            }
        }
        return text
    }
}

//MARK: 数字字符串统一规则
extension ClubGlobalTool {
    
    /*
     (0-9999] - 展示精确数据.
     (1w-10w] - 以w为单位, 精确到小数点后1位：2.9w/3w/etc.
     (10w - 10.1w......)
     */
    func formatNumber(num: String) -> String {

        let number = Int(num) ?? 0
        switch number {
            case 0...9999:
                return "\(number)" // 直接展示精确数据
            case 10000...99999:
                let formatted = Double(number) / 10000.0
                return String(format: "%.1fw", formatted) // 精确到小数点后1位
            case 100000...Int.max:
                let formatted = number / 10000
                return "\(formatted)w" // 以w为单位的整数
            default:
                return "0"
        }
    }
}

//MARK: 打开网盘
extension ClubGlobalTool {
    
    //百度网盘
    func openBaiduNetdisk(urlString: String) {
        if let url = URL(string: "baiduyun://") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            } else {
                print("未安装百度网盘应用，跳转到App Store")
                openLinkInSafariViewController(urlString: urlString)
            }
        }
    }
    
    //夸克网盘
    func openQuarkNetdisk(urlString: String) {
        if let url = URL(string: "quark://") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            } else {
                print("未安装夸克网盘应用，跳转到App Store")
//                openAppStore(appId: "com.quark.browser") // 替换为夸克的 App ID
                openLinkInSafariViewController(urlString: urlString)
            }
        }
    }
    
    //阿里云盘
    func openAliyunDrive(urlString: String) {
        if let url = URL(string: "smartdrive://") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                print("未安装阿里云盘应用，跳转到 App Store")
//                openAppStore(appId: "1477186880") // 阿里云盘的 App Store ID
                openLinkInSafariViewController(urlString: urlString)
            }
        }
    }
    
    func openLinkInSafariViewController(urlString: String) {
        guard let url = URL(string: urlString) else {
            print("无效的 URL")
            return
        }
        let safariVC = SFSafariViewController(url: url)
//        safariVC.preferredControlTintColor = .blue // 自定义控制器颜色
        UIApplication.topController()?.present(safariVC, animated: true, completion: nil)
    }
}
